from django import forms
from .models import FinancialStatement


class FinancialStatementForm(forms.ModelForm):
    class Meta:
        model = FinancialStatement
        fields = ['year', 'total_assets', 'total_liabilities', 'equity', 'revenue', 'net_profit', 'operating_cash_flow']

        # 设置字段的标签和帮助文本
        labels = {
            'year': '财务报表年份',
            'total_assets': '总资产 (元)',
            'total_liabilities': '总负债 (元)',
            'equity': '股东权益 (元)',
            'revenue': '收入 (元)',
            'net_profit': '净利润 (元)',
            'operating_cash_flow': '经营现金流 (元)',
        }

        help_texts = {
            'year': '请输入该财务报表的年份。',
            'total_assets': '请输入公司总资产，单位为元。',
            'total_liabilities': '请输入公司总负债，单位为元。',
            'equity': '请输入公司股东权益，单位为元。',
            'revenue': '请输入公司年度收入，单位为元。',
            'net_profit': '请输入公司年度净利润，单位为元。',
            'operating_cash_flow': '请输入公司年度经营现金流，单位为元。',
        }

        widgets = {
            'year': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '如：2023'}),
            'total_assets': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '如：500000000'}),
            'total_liabilities': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '如：200000000'}),
            'equity': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '如：300000000'}),
            'revenue': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '如：150000000'}),
            'net_profit': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '如：50000000'}),
            'operating_cash_flow': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '如：40000000'}),
        }

    # 自定义字段验证逻辑
    def clean_total_assets(self):
        total_assets = self.cleaned_data.get('total_assets')
        if total_assets <= 0:
            raise forms.ValidationError("总资产必须大于零")
        return total_assets

    def clean_total_liabilities(self):
        total_liabilities = self.cleaned_data.get('total_liabilities')
        if total_liabilities < 0:
            raise forms.ValidationError("总负债不能为负数")
        return total_liabilities

    def clean_equity(self):
        equity = self.cleaned_data.get('equity')
        if equity < 0:
            raise forms.ValidationError("股东权益不能为负数")
        return equity

    def clean_revenue(self):
        revenue = self.cleaned_data.get('revenue')
        if revenue <= 0:
            raise forms.ValidationError("收入必须大于零")
        return revenue

    def clean_net_profit(self):
        net_profit = self.cleaned_data.get('net_profit')
        if net_profit < 0:
            raise forms.ValidationError("净利润不能为负数")
        return net_profit

    def clean_operating_cash_flow(self):
        operating_cash_flow = self.cleaned_data.get('operating_cash_flow')
        if operating_cash_flow < 0:
            raise forms.ValidationError("经营现金流不能为负数")
        return operating_cash_flow
